
define(['jquery', 'dialogTools'], function ($) {
    var utils = {};

    // Ajax
    utils.loadingObjArr = {};
    utils.loading = function (item) {

        if (item.type === 'wheel') {
            if (item.loadingObj === '') {
                return;
            }
            
            var loadingImg = '<img src="' + CONFIG.URL.StaticImg + '/loading.gif"/>',
                bgStr = '';

            if (item.isMask) {
                bgStr = 'background:rgba(255, 255, 255, 0.6);';
            }

            var msgTxt = '<div style="text-align:center; margin-top:6px; color:#666;">' + item.msgTxt + '</div>';

            var loadingBox = '<div style="' + bgStr + '" id="loadingBox_' + item.eleID + '" class="utils-ajax-loading">' + loadingImg + msgTxt + '</div>';
            $('body').append(loadingBox);

            this.loadingObjArr[item.eleID] = $("#loadingBox_" + item.eleID);
            var loadingParentEl = item.loadingObj;

            var boxW = loadingParentEl.outerWidth(),
                boxH = loadingParentEl.outerHeight(),
                boxT = loadingParentEl.offset().top,
                boxL = loadingParentEl.offset().left,
                loadingEl = $("#loadingBox_" + item.eleID),
                imgW = 32,
                imgH = 32;

            if (item.imgW) {
                imgW = item.imgW;
            }
            if (item.imgH) {
                imgH = item.imgH;
            }

            loadingEl.css({
                "position": "absolute",
                "z-index": "100000",
                "text-align": "center",
                "width": boxW + "px",
                "height": boxH + "px",
                "paddingTop": boxH / 2 - imgH / 2 + "px",
                "top": boxT + "px",
                "left": boxL + "px"
            });

            //窗口改变时重置位置
            $(window).bind('resize', function () {
                var loadingParentEl = item.loadingObj;
                var boxW = loadingParentEl.outerWidth(),
                    boxH = loadingParentEl.outerHeight(),
                    boxT = loadingParentEl.offset().top,
                    boxL = loadingParentEl.offset().left;

                loadingEl.css({
                    "width": boxW + "px",
                    "height": boxH + "px",
                    "top": boxT + "px",
                    "left": boxL + "px"
                });

                $(".utils-ajax-mask").css({
                    "width": windowW + "px",
                    "height": windowH + "px"
                });
            });
        } else if (item.type === "belt") {
            if (item.loadingObj === '') {
                return;
            }

            var loadingImg = '<img src="' + CONFIG.URL.StaticImg + '/loading_01.gif"/>',
                bgStr = "";

            bgStr = "background:#fcfcfc; border-radius:8px; padding: 20px 30px; text-align:center; background-image:-ms-linear-gradient(top, rgba(255, 255, 255,1) 0%, rgba(220, 220, 220,1) 100%); background-image: -webkit-gradient(linear, 0% 0%, 0% 100%, from(rgb(255, 255, 255)), to(rgb(220, 220, 220))); -webkit-box-shadow: rgb(102, 102, 102) 2px 2px 5px; box-shadow: rgb(102, 102, 102) 2px 2px 5px; border: 1px solid rgb(217, 215, 211);";

            var msgTxt = '<div style="text-align:center; margin-top:6px; color:#666; text-shadow: rgb(255, 255, 255) 2px 2px 5px; color: rgb(0, 69, 120); white-space: pre-wrap; font-weight: 800; font-size:20px;">' + item.msgTxt + '</div>';

            var windowW = $(window).width();
            var windowH = $(window).height();

            var maskBox = '<div style="background:#fcfcfc; filter:alpha(opacity=30); background:rgba(0, 0, 0, 0.2); z-index:10000; position:fixed; top:0px; left:0px; width:' + windowW + 'px; height:' + windowH + 'px;" class="utils-ajax-mask"></div>';
            var loadingBox = maskBox + '<div style="' + bgStr + '" id="loadingBox_' + item.eleID + '" class="utils-ajax-loading">' + loadingImg + msgTxt + '</div>';
            $("body").append(loadingBox);

            this.loadingObjArr[item.eleID] = $("#" + "loadingBox_" + item.eleID);
            var loadingParentEl = item.loadingObj;

            var boxW = loadingParentEl.outerWidth(),
                boxH = loadingParentEl.outerHeight(),
                boxT = loadingParentEl.offset().top,
                boxL = loadingParentEl.offset().left,
                loadingEl = $("#" + "loadingBox_" + item.eleID),
                imgW = 32,
                imgH = 32;


            if (item.imgW) {
                imgW = item.imgW;
            }
            if (item.imgH) {
                imgH = item.imgH;
            }

            loadingEl.css({
                "position": "fixed",
                "z-index": "100001",
                "min-width": "230px",
                "min-height": "110px",
                "max-width": "400px",
                "top": (windowH - 110) / 2 + "px",
                "left": (windowW - 230)/2 + "px"
            });


            //窗口改变时重置位置
            $(window).bind('resize', function () {
                var windowW = $(window).width();
                var windowH = $(window).height();
                loadingEl.css({
                    "top": (windowH - 110) / 2 + "px",
                    "left": (windowW - 230) / 2 + "px"
                });

                $(".utils-ajax-mask").css({
                    "width": windowW + "px",
                    "height": windowH + "px"
                });
            });
        }
    };

    utils.ajax = function (opts) {
        var that = this,
            eleRandomId = (new Date()).getTime() + parseInt(Math.random() * 100000);

        var _data = $.extend(opts.data || {}, { _fromappdata: $CONFIG._fromappdata });
        $.ajax({
            url: opts.url || "",
            data: opts.data || {},
            async: opts.async || true,
            type: opts.type || "post",
            dataType: opts.dataType || "json",
            ifModified: false,
            timeout: opts.timeout || 60000,
            traditional: false,
            cache: opts.cache || false,
            context: new Object() || $("body"),
            beforeSend: function () {
                if (this["issubmit"]) {
                    return false;
                }
                this["issubmit"] = 1;

                if (opts.loadingObj) {
                    that.loading({
                        eleID: eleRandomId,
                        loadingObj: opts.loadingObj.el || "",
                        msgTxt: opts.loadingObj.msg || '载入中...',
                        isMask: opts.loadingObj.isMask || false,
                        type: opts.loadingObj.type || "wheel"
                    });
                }
                if (opts.start) {
                    opts.start();
                }
            },
            success: function (data) {
                if (opts.success) {
                    opts.success(data);
                }
            },
            error: function (data, status, error) {
                if (opts.error) {
                    opts.error(data);
                } else {
                    if (status == 'timeout') {
                        $.dialog.tips({
                            status: "warning",
                            content: '网络超时，请重试！'
                        });
                    } else {
                        $.dialog.tips({
                            status:  "warning",
                            content: '网络异常，请重试！'
                        });
                    }
                }
            },
            complete: function (o) {
                this["issubmit"] = 0;
                if (opts.loadingObj) {
                    if (that.loadingObjArr[eleRandomId]) {
                        $(".utils-ajax-mask").remove();
                        that.loadingObjArr[eleRandomId].remove();
                    }
                }
                if (opts.complete) {
                    opts.complete();
                }
            }
        });
    };

    //滚动加载
    utils.scroll = function (options, callback) {
        var _opt = $.extend({
            el: null,
            url: '',
            data: {},
            dataType: 'json',
            page: 1,
            pagesize: 10,
            loadingImg: '',
            loadingText: '正在加载中,请稍后...',
            open: true,
            doneText: '没有更多了...',
            error: function () {
            }
        }, options || {});

        //对象
        var _this = $(_opt.el);
        var tempMaxFloor = 0;

        //合并对象
        _opt.data = $.extend({ page: _opt.page, pagesize: _opt.pagesize }, _opt.data || {});

        //内置对象
        _opt.loading = $('<div class="scroll-tips" style="text-align: center;padding:15px;">' + _opt.loadingText + '</div>');
        if (_opt.open) {
            _opt.done = $('<div class="scroll-tips" style="text-align: center;padding:15px;">' + _opt.doneText + '</div>');
        }
        _opt.on = true;

        _opt.doing = function () {
            $.ajax({
                url: _opt.url,
                type: 'post',
                data: _opt.data,
                dataType: _opt.dataType,
                success: function (json) {
                    if (json &&
                        json.data &&
                        json.data.items) {

                        if (callback) {
                            callback(json, { page: _opt.data.page });
                        }
                        if (_opt.data.page == 1) {
                            tempMaxFloor = json.data.total;
                        }

                        if (json.data.items.length > 0) {
                            //递增+1
                            ++_opt.data.page;
                        } else {
                            if (_opt.open) {
                                //没有更多了..
                                _opt.done.appendTo(_this);

                                setTimeout(function () {
                                    _opt.done.remove();
                                },3000);
                            }
                        }
                    } else {
                        if (_opt.open) {
                            //没有更多了..
                            _opt.done.appendTo(_this);
                        }
                    }
                },
                error: function () {
                    if (_opt.error) {
                        _opt.error();
                    }
                },
                beforeSend: function () {
                    if (_opt.open) {
                        _opt.done.remove();
                    }
                    _opt.loading.appendTo(_this);
                },
                complete: function () {
                    _opt.on = true;
                    _opt.loading.remove();
                }
            });
        };

        if (_opt.el) {
            $(_opt.el).off().scroll(function () {
                //可见高度
                var _view = _this.height();
                //包含不可见高度
                var _content = _this.get(0).scrollHeight;
                //滚动高度
                var _scrollTop = _this.scrollTop();

                if (_content - _view - _scrollTop <= 50) {
                    if (_opt.on) {
                        _opt.on = false;
                        var latestMaxFloor = _this.find(".item").first().data("floor");
                        var tempNum = Math.floor((tempMaxFloor - 1) / 10);
                        var latestNum = Math.floor((latestMaxFloor - 1) / 10);
                        _opt.data.page += (latestNum - tempNum);
                        _opt.doing();
                    }
                }
            });

            _opt.doing();
        }
    };

    // 随机取出数组中的某一个或几个
    utils.randomArr = function (arr, num) {
        var that = this;
        // 新建一个数组,将传入的数组复制过来,用于运算,而不要直接操作传入的数组;
        var temp_array = new Array();
        for (var index in arr) {
            temp_array.push(arr[index]);
        }

        // 取出的数值项,保存在此数组
        var return_array = new Array();

        for (var i = 0; i < num; i++) {
            // 判断如果数组还有可以取出的元素,以防下标越界
            if (temp_array.length > 0) {
                // 在数组中产生一个随机索引
                var arrIndex = Math.floor(Math.random() * temp_array.length);
                // 将此随机索引的对应的数组元素值复制出来
                return_array[i] = temp_array[arrIndex];

                // 然后删掉此索引的数组元素,这时候temp_array变为新的数组
                temp_array.splice(arrIndex, 1);
            } else {
                // 数组中数据项取完后,退出循环,比如数组本来只有10项,但要求取出20项.
                break;
            }
        }
        return return_array;
    };

    //时间Format
    Date.prototype.Format = function (fmt) { //author: meizz 
        var o = {
            "M+": this.getMonth() + 1, //月份 
            "d+": this.getDate(), //日 
            "h+": this.getHours(), //小时 
            "m+": this.getMinutes(), //分 
            "s+": this.getSeconds(), //秒 
            "q+": Math.floor((this.getMonth() + 3) / 3), //季度 
            "S": this.getMilliseconds() //毫秒 
        };
        if (/(y+)/.test(fmt))
            fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
        for (var k in o)
            if (new RegExp("(" + k + ")").test(fmt))
                fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
        return fmt;
    }

    //字符串Format
    String.prototype.format = function () {
        var args = arguments;
        return this.replace(/\{(\d+)\}/g,
            function (m, i) {
                return args[i];
            });
    };

    String.prototype.replaceAll = function (s1, s2) {
        var r = new RegExp(s1.replace(/([\(\)\[\]\{\}\^\$\+\-\*\?\.\"\'\|\/\\])/g, "\\$1"), "ig");
        return this.replace(r, s2);
    };

    utils.console = function(msg,type){
        if(window.debug){
            console.log(msg);
        }
    }

    utils.loadUniversalConfig = function(wallId,callback){
        var timestamp = (new Date).getTime();

        var url =$CONFIG.REMOTE.NewApiUrl+ 'EventV5/Common/GetUploadFileByPath.ashx?filePath=/Uploads/Files/wxchatwall_rechat' + wallId + '.json&callname=?';

        $.ajax({
                type: "get",
                // async: false,
                url: url,
                dataType: "json",
                jsonp: "callback",
                //jsonpCallback:"flightHandler",//自定义的jsonp回调函数名称，默认为jQuery自动生成的随机函数名，也可以写"?"，jQuery会自动为你处理数据
                success: function(jdata) {
                    callback && callback(jdata);
                },
                error: function(xhr, ajaxOptions, thrownError) {
                    
                }
            });
    }

    utils.saveUniversalConfig = function(wallId,data,callback){

        var sendbody = $.extend(true, {}, data);

        var url = $CONFIG.REMOTE.NewApiUrl + 'EventV5/Common/GetUploadFileByPath.ashx?filePath=/Uploads/Files/wxchatwall_rechat' + wallId + '.json';

        $.ajax({
            type: "post",
            // async: false,
            url: url,
            data: { content: JSON.stringify(sendbody) },
            dataType: "json",
            //jsonpCallback:"flightHandler",//自定义的jsonp回调函数名称，默认为jQuery自动生成的随机函数名，也可以写"?"，jQuery会自动为你处理数据
            success: function(json) {
                json = JSON.parse(json);
                callback && callback(json);
            },
            error: function() {

            }
        });

    }

    return utils;
});